package com.happy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.happy.dao.AnswerMapper;
import com.happy.entity.AnswerEntity;
import com.happy.entity.UserEntity;
import com.happy.service.IAnswerService;
import com.happy.util.StateEnum;
import com.happy.util.StateException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 17:26 2021/1/31
 * @return
 */
@Service
public class AnswerServiceImpl extends ServiceImpl<AnswerMapper, AnswerEntity> implements IAnswerService {


    @Resource
    private AnswerMapper answerMapper;

    @Override
    public List<AnswerEntity> queryList ( AnswerEntity answerEntity ) {
        QueryWrapper<AnswerEntity> queryWrapper = new QueryWrapper<> ();
        if ( answerEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        if ( answerEntity.getOptionId () != null ) {
            queryWrapper.eq ( "optionId", answerEntity.getOptionId () );
        }
        if ( answerEntity.getSubjectId () != null ) {
            queryWrapper.eq ( "subjectId", answerEntity.getSubjectId () );
        }
        List<AnswerEntity> answerEntities = baseMapper.selectList ( queryWrapper );
        return answerEntities;
    }

    @Override
    public AnswerEntity querySingle ( AnswerEntity answerEntity ) {
        if ( answerEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        answerEntity = answerMapper.querySingle ( answerEntity );
        return answerEntity;
    }

    @Override
    public AnswerEntity addSingle ( AnswerEntity answerEntity ) {
        if ( answerEntity == null ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        int insert = baseMapper.insert ( answerEntity );
        if ( insert == 0 ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return answerEntity;
    }

    @Override
    public boolean addBatch ( List<AnswerEntity> answerEntities, UserEntity userEntity, int recordId ) {
        if ( answerEntities == null || answerEntities.size () == 0 ) {
            throw new StateException ( StateEnum.REQUEST_PARAM_EXCE );
        }
        for ( AnswerEntity answerEntity : answerEntities ) {
            answerEntity.setRecordId ( recordId );
            answerEntity.setUserId ( userEntity.getId () );
            answerEntity.setCreateTime ( new Date () );
        }
        boolean b = this.saveBatch ( answerEntities, answerEntities.size () );
        if ( ! b ) {
            throw new StateException ( StateEnum.INSERT_EXCE );
        }
        return b;
    }
}
